package org.example.ims.Service.Base.Impl;

import org.example.ims.Entity.Base.Warehouse;
import org.example.ims.Repository.Base.WarehouseRepository;
import org.example.ims.Service.Base.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;


@Service("warehouseService")
public class WarehouseServiceImpl implements WarehouseService {
    @Autowired
    private  WarehouseRepository warehouseRepository;


    @Override
    public Warehouse addWarehouse(Warehouse warehouse) {
        warehouse.setUsedCapacity(0);
        return warehouseRepository.save(warehouse);
    }


    @Override
    public Warehouse addWarehouse2(Warehouse warehouse) {
        if (!warehouseRepository.existsById(99)) {
            Warehouse temp = new Warehouse();
            temp.setWarehouseId(99); // 设置 ID，但下面会清除
            temp.setWarehouseName("Manual Insert");

            // 强制清空 ID，让 JPA 认为是新实体
            temp.setWarehouseId(null);

            warehouseRepository.save(temp); // 会执行 INSERT
        } else {
            throw new RuntimeException("ID already exists");
        }
        return null;
    }

    @Override
    public Optional<Warehouse> findWarehouseById(Integer warehouseId) {
        return warehouseRepository.findById(warehouseId);
    }

    @Override
    public Page<Warehouse> findAllWarehouses(Integer page, Integer size) {
        return warehouseRepository.findAll(PageRequest.of(page, size));
    }

    @Override
    public Page<Warehouse> searchWarehouses(String name, String status, Integer page, Integer size) {
        return warehouseRepository.searchWarehouses(
                name, status, PageRequest.of(page, size)
        );
    }

    @Override
    public Warehouse updateWarehouse(Integer warehouseId, Warehouse warehouseDetails) {
        Warehouse newWarehouse = warehouseRepository.findById(warehouseId)
                .orElseThrow(() -> new RuntimeException("Warehouse does not exist"));
        warehouseDetails.setUsedCapacity(newWarehouse.getUsedCapacity());
        return warehouseRepository.save(warehouseDetails);
    }

    @Override
    public void deleteWarehouseById(Integer warehouseId) {
        if (!warehouseRepository.existsById(warehouseId)) {
            throw new RuntimeException("Warehouse does not exist");
        }
        warehouseRepository.deleteById(warehouseId);
    }
}